<template>
	<el-form ref="elFormRef" :model="formData" :rules="rules" label-width="100px" :inline="false">
		<el-row :gutter="20">
			<el-col v-for="item in schemas" :key="item.field" v-bind="item.colProps || { span: 12 }">
				<el-form-item :label="item.label" :prop="item.field">
					<!-- slot 优先 -->
					<slot v-if="item.slot" :name="item.slot" :row="formData" :field="item.field" :item="item" />
					<!-- 渲染内置组件 -->
					<component
						v-else
						:is="getComponent(item)"
						v-model="formData[item.field]"
						v-bind="item.componentProps"
						:show-password="item.showPassword"
					>
						<!-- 处理Select选项 -->
						<template v-if="item.component === 'Select'">
							<el-option
								v-for="opt in item.options"
								:key="opt.value"
								:label="opt.label"
								:value="opt.value"
							/>
						</template>
					</component>
				</el-form-item>
			</el-col>
		</el-row>
	</el-form>
</template>

<script setup lang="ts">
// import { reactive, watch, ref, defineExpose } from "vue";
import type { FormSchema } from "./type";
import { ElForm, ElInput, ElSelect, ElOption, ElDatePicker } from "element-plus";
const formData = defineModel<any>("formData");
defineProps<{
	schemas: FormSchema[];
	rules?: Record<string, any>;
}>();

const elFormRef = ref<InstanceType<typeof ElForm>>();

/** 组件映射 */
const getComponent = (item: FormSchema) => {
	switch (item.component) {
		case "Input":
			return ElInput;
		case "Select":
			return ElSelect;
		case "DatePicker":
			return ElDatePicker;
		case "Custom":
			return item.slot || "div";
		default:
			return "el-input";
	}
};

/** 对外暴露方法 */
defineExpose({
	validate: () => elFormRef.value?.validate(),
	resetFields: () => elFormRef.value?.resetFields(),
});
</script>
